package tr.edu.yildiz.ce.dap.apm.process;

import java.io.IOException;
import java.math.BigInteger;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import javax.xml.bind.JAXBException;

import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;
import tr.edu.yildiz.ce.dap.appagent.service.MessageConverter;
import tr.edu.yildiz.ce.dap.appagent.util.AgentProperties;

public class ProxyBroadCaster implements Runnable{
	
	String address;
	// ConfConstants.proxy_port
	int port ;
	
	String mcastAddress;
	int mcastPort;
	
	public ProxyBroadCaster(String address,int port,String mcastAddress,int mcastPort){
		this.address = address;
		this.port = port;
		this.mcastAddress = mcastAddress;
		this.mcastPort = mcastPort;
	}
	

	public void run() {
		MulticastSocket socket = null;
		try {
			socket = new MulticastSocket();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		DapMessage dapMessage = new DapMessage();
		dapMessage.setProxyAddress(address);
		dapMessage.setProxyPort(new BigInteger(String.valueOf(port)));
		
		String xml = null;
		try {
			xml = MessageConverter.convertToXML(dapMessage);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		 while (true) {
		        try {
		            byte[] buf = xml.getBytes();
		            InetAddress group = InetAddress.getByName(mcastAddress);
		            DatagramPacket packet;
		            packet = new DatagramPacket(buf, buf.length, 
		                                        group, mcastPort);
		            socket.send(packet);

		            try {
		                Thread.sleep(1000);
		            } catch (InterruptedException e) { }
		        } catch (IOException e) {
		            e.printStackTrace();
		        } 
		    }

		
	}

}
